package me.firstapp.manage.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.weixin.JsonOperator;
import me.firstapp.common.utils.MD5Utils;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.manage.common.BaseManage;
import me.firstapp.module.weixin.system.Operator;
import me.firstapp.service.weixin.system.OperatorService;

@Controller
@RequestMapping(value = "/loginManage")
public class LoginManageAct extends BaseManage {

	private Logger logger = LoggerFactory.getLogger(LoginManageAct.class);

	@Autowired
	private OperatorService operatorService;

	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public void login(String name, String password, String code, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<JsonOperator> result = new SingleObject<>();
		try {
			Operator operator = operatorService.findOperatorByName(name);
			if (null == operator) {
				throw new ServiceException("error", "操作员不存在");
			}
			String _code = (String) request.getSession().getAttribute(operator.getEmail());
			if (!code.equals(_code)) {
				throw new ServiceException("error", "验证码不正确");
			}
			if (!MD5Utils.verify(password, operator.getPassword())) {
				throw new ServiceException("error", "密码不正确");
			}
			String loginToken = StrUtils.getLoginToken();
			request.getSession().setAttribute("loginToken", loginToken);
			request.getSession().setAttribute("login_operator_" + loginToken,
					new JsonOperator(operator.getEmail(), name));
			request.getSession().removeAttribute(operator.getEmail());
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}

		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/logout.do", method = RequestMethod.POST)
	public void logout(HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			String loginToken = (String) request.getSession().getAttribute("loginToken");
			JsonOperator jsonOperator = (JsonOperator) request.getSession()
					.getAttribute("login_operator_" + loginToken);
			request.getSession().removeAttribute("loginToken");
			request.getSession().removeAttribute("login_operator_" + loginToken);
			request.getSession().removeAttribute(jsonOperator.getEmail());
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}

		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/sendEmailCode.do", method = RequestMethod.POST)
	public void sendEmailCode(String name, String password, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<String> resultJsonObject = new SingleObject<String>();
		try {
			if (StrUtils.isNULL(name)) {
				throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "`账号");
			}
			Operator operator = operatorService.findOperatorByName(name);
			if (null == operator) {
				throw new ServiceException("error", "操作员不存在");
			}
			if (!MD5Utils.verify(password, operator.getPassword())) {
				throw new ServiceException("error", "密码不正确");
			}
			String email = operator.getEmail();
			String code = StrUtils.getVerifyCode(6);
			String content = "<p>你的验证码为：<strong>" + code + "</strong>，两分钟之内有效。【FirstApp.Me】</p>";
			sendEmail(email, content, "登录验证");
			request.getSession().setAttribute(email, code);
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			e.printStackTrace();
			resultJsonObject.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, resultJsonObject);
	}

	private void sendEmail(String toEmail, String content, String subject) {
		StringBuilder url = new StringBuilder("http://api.sendcloud.net/apiv2");
		url.append("/mail/send");
		url.append("?apiUser=").append("keanu_test_p1hmrQ");
		url.append("&apiKey=").append("EyaOQKf7w7Ci4GyS");
		url.append("&from=").append("firstapp@qq.com");
		url.append("&to=").append(toEmail);
		url.append("&subject=").append(subject);
		url.append("&html=").append(content);

		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> responseEntity = restTemplate.exchange(url.toString(), HttpMethod.POST, null,
				String.class);
		String resultStr = responseEntity.getBody();
		logger.info("发送邮件返回结果==》" + resultStr);
		if (StrUtils.isNotNULL(resultStr)) {
			JSONObject jsonObject = JSONObject.parseObject(resultStr);
			int statusCode = jsonObject.getIntValue("statusCode");
			if (statusCode == 200) {
			} else {
				logger.info("发送邮件失败，失败信息=》" + statusCode + "," + jsonObject.getString("message"));
				throw new ServiceException(statusCode + "", jsonObject.getString("message"));
			}
		}
	}
}
